import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

const rightCode = 0 // 正确返回code
const logoutCode = 401 // 用户失效
// const testUrl = 'http://192.168.1.66:8081/kaihit'

// 自定义配置新建一个 axios 实例
const service = axios.create({
//   baseURL: '/66/', // url = base url + request url
  //   baseURL: '/156/',
  // baseURL: './', // 公网/182
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // request timeout
})

let ifBusing
if (sessionStorage.getItem('ifBusing')) {
  ifBusing = sessionStorage.getItem('ifBusing')
} else {
  sessionStorage.setItem('ifBusing', false)
  ifBusing = false
}

// 添加请求拦截器
service.interceptors.request.use(config => {
  // token根据实际要求设置
  // console.log(config)
  // console.log(store)
  if (store.getters.token) {
    // console.log('=========store里面有token')
    // config.headers['token'] = getToken() // token根据实际要求设置
    config.headers['Authorization'] = 'bearer' + ' ' + getToken()
    // console.log(config.headers)
    // config.headers['token'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ6aGFuZ2ZhbiIsImlhdCI6MTU5OTgxNTQxNiwiZXhwIjoxNjAxMjg2NjQ1fQ.UbAEoG_ZfH69m6GC7gDBRR_RS7fBERHwAmh0y4K_KfpTniEPs8NQIndGB_pCAyeo_8NiCYHuGKYm4q1TOsVLyA' // token根据实际要求设置
  }
  // console.log('store里面没有token')
  return config
})

// 添加相应拦截器
service.interceptors.response.use(response => {
  const res = response.data
  //   console.log(res)
  if (res.code && res.code !== rightCode) {
    if (res.code === logoutCode) {
      if (!ifBusing && store?.getters?.hasToken) {
        sessionStorage.setItem('ifBusing', true)
        ifBusing = true
        MessageBox.confirm(res.msg + ',3秒后返回登录', '重新登录', {
          confirmButtonText: '重新登录',
          showCancelButton: false,
          showClose: false,
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            router.replace({
              path: '/'
            })
            // location.reload()
          })
        })
        setTimeout(() => {
          MessageBox.close()
          store.dispatch('user/resetToken').then(() => {
            router.replace({
              path: '/login'
            })
            // location.reload()
          })
        }, 3 * 1000)
      } else {
        store.dispatch('user/resetToken').then(() => {
          router.replace({
            path: '/'
          })
          // location.reload()
        })
      }
      return Promise.reject(new Error(res.msg || 'ERROR'))
    }
    // return Promise.reject(new Error(res.msg || 'ERROR'))
  } else {
    sessionStorage.setItem('ifBusing', false)
    ifBusing = false
  }
  return res
}, err => {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '请求错误'
        break
      case 401:
        err.message = '未授权，请登录'
        break
      case 403:
        err.message = '拒绝访问'
        break
      case 404:
        err.message = `请求地址出错: ${err.response.config.url}`
        break
      case 408:
        err.message = '请求超时'
        break
      case 500:
        err.message = '服务器内部错误'
        break
      case 501:
        err.message = '服务未实现'
        break
      case 502:
        err.message = '网关错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网关超时'
        break
      case 505:
        err.message = 'HTTP版本不受支持'
        break
      default:
    }
  }
  if (!ifBusing) {
    sessionStorage.setItem('ifBusing', true)
    ifBusing = true
    if (err.message.indexOf('Network Error') >= 0) {
      Message({
        type: 'error',
        message: '网络连接失败，请稍后再试',
        offset: 60,
        duration: 3 * 1000
      })
    } else {
      Message({
        type: 'error',
        message: '网络连接失败，请稍后再试',
        offset: 60,
        duration: 3 * 1000
      })
    }
  }
  return Promise.reject(err)
})

export default service
